#coding:utf-8
"""
Xml format
<tag attrib1 = 1> text </tag> tail
"""

import os
from xml.sax.saxutils import escape, unescape

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

def parse_xml_to_dict(path, node_name, key_name = "id"):

    all_infos = {}

    root = ET.parse(path)
    node_iter = root.getiterator(node_name)  #
    for node in node_iter:
        info = {}
        for field in node:
            key = field.tag.strip()
            value = field.text
            if value:
                value = value.strip()
            info[key] = value

        if not all_infos.get(key_name):
            all_infos[info.get(key_name)] = info

    return all_infos

def parse_dict_to_xml(path, all_infos, root_name, node_name):
    pass

# 过滤xml文件的一行数据
def filter_line(line):
    s = line.strip()
    begin_tag_finish_pos = s.find(">") + 1
    end_tag_start_pos = s.rfind("<")

    if end_tag_start_pos < begin_tag_finish_pos:
        return line

    #TODO: 暂时如果一行有多个xml对，不做处理
    # 此处有bug
    lt_count = s.count("<")
    gt_count = s.count(">")
    if (lt_count > 2 and lt_count % 2 == 0) or \
            (gt_count > 2 and gt_count % 2 == 0):
        return line

    text = s[begin_tag_finish_pos : end_tag_start_pos]
    return "%s%s%s\n" % (s[0 : begin_tag_finish_pos],
            escape(unescape(text)),
            s[end_tag_start_pos :])

def filter_xml_escape_chars(xml_path):
    old_xml_path = xml_path + ".old"
    os.rename(xml_path, old_xml_path)

    old_xml_file = open(old_xml_path, "r")
    new_xml_file = open(xml_path, "a")

    old_str = None
    new_str = ""
    for line in old_xml_file:
        new_xml_file.write(filter_line(line))

    old_xml_file.close()
    new_xml_file.close()
    os.remove(old_xml_path)
